// 公众号授权弹窗功能实现
$(document).ready(function () {
    createWechatAuthModal();
});

// 创建公众号授权弹窗
function createWechatAuthModal() {
    if ($('#wechatAuthModal').length > 0) return;

    const modalHtml = `
        <div id="wechatAuthModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden transition-opacity duration-300">
            <div class="bg-white rounded-2xl shadow-2xl w-full max-w-3xl overflow-hidden transform transition-all scale-95 hover:scale-100 duration-200">
                <div class="p-6">
                    <!-- 标题栏 - 新增模式显示 -->
                    <div class="flex justify-between items-center mb-6 border-b pb-3">
                        <div class="flex items-center">
                            <i class="fa fa-weixin text-green-500 mr-2 text-2xl"></i>
                            <h2 id="modalTitle" class="text-xl font-bold text-gray-800">已授权公众号</h2>
                        </div>
                        <button id="closeWechatAuthModalBtn" class="text-gray-400 hover:text-gray-600 transition">
                            <i class="fa fa-times text-xl"></i>
                        </button>
                    </div>
                    
                    <!-- 已授权公众号列表 -->
                    <div id="wechatAccountsList" class="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-6">
                        <div class="col-span-full text-center text-gray-500 py-8">
                            <i class="fa fa-spinner fa-spin mr-2 text-green-500"></i>
                            <span class="text-gray-600">正在加载已授权公众号...</span>
                        </div>
                    </div>
                    
                    <!-- 多选操作按钮 -->
                    <div id="multiSelectActions" class="hidden flex justify-end space-x-3 pt-3 border-t">
                        <button id="cancelSelectionBtn" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition">
                            取消选择
                        </button>
                        <button id="confirmMultiPublishBtn" class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition">
                            发布到已选公众号
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    $('body').append(modalHtml);
    $('#closeWechatAuthModalBtn').on('click', hideWechatAuthModal);
    $('#cancelSelectionBtn').on('click', cancelMultiSelection);
    $('#confirmMultiPublishBtn').on('click', confirmMultiPublish);
}

// 显示公众号授权弹窗 - 核心修改：批量文档模式默认启用多选
function showWechatAuthModal(documentId, documentTitle, mode) {
    // 确保documentId和documentTitle是有效的
    if (documentId && documentTitle) {
        // 确保documentId不是空字符串
        if (documentId === '') {
            alert('无法发布文档到公众号：文档ID无效，请刷新页面后重试');
            console.error('调用showWechatAuthModal时documentId为空字符串');
            return;
        }

        // 存储文档信息
        sessionStorage.setItem('currentDocumentId', documentId);
        sessionStorage.setItem('currentDocumentTitle', documentTitle);

        // 存储模式（单选/多选）- 核心修改：批量文档模式强制使用多选
        let publishMode = mode || 'single';
        if (documentId === 'batch') {
            publishMode = 'batch'; // 批量文档模式强制启用多选
            // 更新弹窗标题，明确当前模式
            $('#modalTitle').text('批量发布到公众号');
        } else {
            $('#modalTitle').text('已授权公众号');
        }
        sessionStorage.setItem('publishMode', publishMode);

        // 显示弹窗
        $('#wechatAuthModal').removeClass('hidden');

        // 清空之前的选择
        selectedAccounts = [];

        // 加载公众号列表
        loadWechatAccounts();
    } else {
        alert('无法发布文档到公众号：缺少文档信息，请刷新页面后重试');
        console.error('调用showWechatAuthModal时缺少documentId或documentTitle参数');
    }
}

// 隐藏公众号授权弹窗
function hideWechatAuthModal() {
    $('#wechatAuthModal').addClass('hidden');
    // 重置标题
    $('#modalTitle').text('已授权公众号');
}

// 存储选中的公众号 - 修复：移到函数外部，确保全局可访问
let selectedAccounts = [];

// 加载已授权公众号列表
function loadWechatAccounts() {
    const accountsList = $('#wechatAccountsList');
    accountsList.empty();

    showLoadingOverlay('正在加载已授权公众号...');

    console.log('开始请求已授权公众号列表，URL: /api/documents/wechat/accounts');

    // 从后端API获取真实数据
    $.ajax({
        url: '/api/documents/wechat/accounts',
        type: 'GET',
        success: function (response) {
            hideLoadingOverlay();
            if (response.code === 0 && response.data) {
                accountsList.empty(); // 修复：清空列表，避免重复渲染

                if (response.data.length > 0) {
                    // 渲染公众号卡片
                    response.data.forEach(account => {
                        console.log('原始公众号数据:', account);

                        // 进行字段映射，确保前端代码能正确访问字段
                        // 根据后端返回的实际数据格式进行映射
                        const mappedAccount = {
                            id: account.id || '',
                            nickname: account.account_name || '未知公众号',
                            headImgUrl: account.head_img_url || 'https://via.placeholder.com/100?text=No+Image', // 使用后端返回的头像或默认头像
                            authorizerAppid: account.appid || '',
                            serviceTypeInfo: account.account_type || 0,
                            status: account.auth_status || 0 // 1表示已授权，0表示未授权
                        };

                        console.log('映射后的公众号数据:', mappedAccount);

                        const accountHtml = `
                                <div class="wechat-account-card bg-white p-5 rounded-xl shadow hover:shadow-lg border border-gray-200 cursor-pointer transition-transform transform hover:-translate-y-1" 
                                     data-account-id="${mappedAccount.id}" data-account-name="${mappedAccount.nickname}">
                                    <div class="flex items-center justify-between">
                                        <div class="flex items-center">
                                            <div class="relative">
                                                <img src="${mappedAccount.headImgUrl}" alt="${mappedAccount.nickname}" class="w-14 h-14 rounded-full mr-4 border border-gray-300 shadow-sm">
                                                <div class="absolute top-0 right-0 rounded-full p-1 shadow-md ${getAuthStatusClass(mappedAccount.status)}">
                                                    <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"></path>
                                                    </svg>
                                                </div>
                                            </div>
                                            <div>
                                                <div class="font-semibold text-gray-800">${mappedAccount.nickname}</div>
                                                <div class="text-sm text-gray-500">${mappedAccount.authorizerAppid}</div>
                                            </div>
                                        </div>
                                        <div class="multi-select-checkbox w-6 h-6 border-2 border-gray-300 rounded flex items-center justify-center" style="display: none;"></div>
                                    </div>
                                </div>
                            `;
                        accountsList.append(accountHtml);
                    });

                    // 绑定公众号卡片点击事件
                    bindAccountCardEvents();
                } else {
                    // 没有已授权的公众号
                    const emptyHtml = `
                        <div class="col-span-full text-center text-gray-500 py-8">
                            <i class="fa fa-weixin text-4xl text-green-300 mb-3"></i>
                            <p class="text-gray-600 mb-4">暂无已授权的公众号</p>
                            <button id="addFirstAuthBtn" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg transition">
                                立即授权
                            </button>
                        </div>
                    `;
                    accountsList.append(emptyHtml);

                    $('#addFirstAuthBtn').on('click', function () {
                        showAuthQRCodeModal();
                    });
                }

                // 新增公众号授权按钮 - 无论加载是否成功都显示
                const addAuthHtml = `
                <div id="addWechatAuthCard" class="bg-gradient-to-r from-blue-50 to-blue-100 p-6 rounded-xl border-2 border-dashed border-blue-300 flex flex-col items-center justify-center cursor-pointer hover:shadow-lg transition-transform transform hover:-translate-y-1">
                    <div class="w-14 h-14 rounded-full bg-blue-200 flex items-center justify-center mb-3">
                        <svg class="w-7 h-7 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                        </svg>
                    </div>
                    <div class="text-sm font-medium text-blue-700">新增公众号授权</div>
                </div>
            `;
                accountsList.append(addAuthHtml);

                $('#addWechatAuthCard').on('click', function () {
                    showAuthQRCodeModal();
                });
            } else {
                // 修复：服务器返回错误时的处理逻辑
                renderErrorState('服务器返回异常，请稍后重试', accountsList);
            }
        },
        error: function (xhr, status, error) {
            hideLoadingOverlay();
            accountsList.empty(); // 修复：清空列表，避免显示加载中状态

            console.error('公众号授权功能加载失败:', {
                status: status,
                error: error,
                statusCode: xhr.status,
                responseText: xhr.responseText,
                url: '/api/documents/wechat/accounts'
            });

            // 更详细的错误信息
            let errorMessage = '公众号授权功能尚未加载完成，请刷新页面重试';
            if (status === 'timeout') {
                errorMessage = '网络连接超时，请检查网络后重试';
            } else if (status === 'error') {
                if (xhr.status === 404) {
                    errorMessage = 'API接口不存在，请检查服务器配置';
                } else if (xhr.status === 500) {
                    errorMessage = '服务器内部错误，请稍后重试';
                } else {
                    errorMessage = `服务器连接失败 (${xhr.status})，请稍后重试`;
                }
            }

            renderErrorState(errorMessage, accountsList);
        }
    });
}

// 移除之前可能存在的绑定，避免重复绑定 - 修复：移到bindAccountCardEvents函数内，避免提前执行
function bindAccountCardEvents() {
    // 移除之前可能存在的绑定，避免重复绑定
    $(document).off('click', '.wechat-account-card');
    $(document).off('click', '.multi-select-checkbox');

    // 获取当前发布模式
    const publishMode = sessionStorage.getItem('publishMode') || 'single';

    // 显示或隐藏多选相关元素
    const multiSelectCheckboxes = $('.multi-select-checkbox');
    const multiSelectActions = $('#multiSelectActions');

    if (publishMode === 'batch') {
        // 多选模式：显示多选框和操作按钮
        multiSelectCheckboxes.css('display', 'flex');
        multiSelectActions.removeClass('hidden');

        console.log('启用多选模式');
    } else {
        // 单选模式：隐藏多选框和操作按钮
        multiSelectCheckboxes.css('display', 'none');
        multiSelectActions.addClass('hidden');

        console.log('启用单选模式');
    }

    // 卡片点击事件
    $(document).on('click', '.wechat-account-card', function (e) {
        e.preventDefault();
        e.stopPropagation();

        // 如果点击的是多选框区域，执行多选逻辑
        if ($(e.target).closest('.multi-select-checkbox').length > 0) {
            toggleAccountSelection(this);
            updateMultiSelectActions();
            return;
        }

        const accountId = $(this).data('account-id');
        const accountName = $(this).data('account-name');

        console.log('点击公众号卡片:', {
            accountId: accountId,
            accountName: accountName,
            publishMode: publishMode,
            element: this
        });

        // 防止重复点击
        if ($(this).hasClass('processing')) {
            console.log('正在处理中，忽略重复点击');
            return false;
        }

        $(this).addClass('processing');

        if (publishMode === 'batch') {
            // 多选模式：切换选中状态
            toggleAccountSelection(this);
            updateMultiSelectActions();
            setTimeout(() => {
                $(this).removeClass('processing');
            }, 500);
        } else {
            // 单选模式：直接发布
            publishToSelectedAccount(accountId, accountName);
            setTimeout(() => {
                $(this).removeClass('processing');
            }, 2000);
        }
    });

    // 多选框点击事件
    $(document).on('click', '.multi-select-checkbox', function (e) {
        e.stopPropagation();
        const card = $(this).closest('.wechat-account-card')[0];
        toggleAccountSelection(card);
        updateMultiSelectActions();
    });
}

// 渲染错误状态
function renderErrorState(message, container) {
    container.empty(); // 修复：清空容器，避免错误信息重复
    const errorHtml = `
        <div class="col-span-full text-center text-gray-500 py-8">
            <i class="fa fa-exclamation-circle text-red-500 mr-2 text-2xl"></i>
            <p class="text-gray-600 mb-4">${message}</p>
            <button id="retryLoadAccountsBtn" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition">
                <i class="fa fa-refresh mr-1"></i> 重试
            </button>
        </div>
    `;
    container.append(errorHtml);

    // 重试按钮点击事件
    $('#retryLoadAccountsBtn').on('click', function () {
        loadWechatAccounts();
    });
}

// 切换公众号选择状态
function toggleAccountSelection(card) {
    const checkbox = $(card).find('.multi-select-checkbox');
    const isSelected = checkbox.hasClass('selected');
    const accountId = $(card).data('account-id');
    const accountName = $(card).data('account-name');

    if (isSelected) {
        // 取消选择
        checkbox.removeClass('selected bg-green-500 border-green-500');
        checkbox.empty();
        $(card).removeClass('border-green-500 shadow-green-200');

        // 从选中列表中移除
        selectedAccounts = selectedAccounts.filter(item => item.id !== accountId);
    } else {
        // 选中
        checkbox.addClass('selected bg-green-500 border-green-500');
        checkbox.html('<svg class="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"></path></svg>');
        $(card).addClass('border-green-500 shadow-green-200');

        // 添加到选中列表
        selectedAccounts.push({ id: accountId, name: accountName });
    }
}

// 更新多选操作按钮的显示状态
function updateMultiSelectActions() {
    const selectedCount = selectedAccounts.length; // 修复：使用全局选中列表计数
    const actionsDiv = $('#multiSelectActions');
    const publishMode = sessionStorage.getItem('publishMode') || 'single';

    // 批量模式下始终显示操作栏（即使未选择），提示用户选择
    if (publishMode === 'batch') {
        actionsDiv.removeClass('hidden');
        $('#confirmMultiPublishBtn').text(selectedCount > 0
            ? `发布到已选公众号(${selectedCount})`
            : '请选择公众号');

        // 未选择时禁用确认按钮
        if (selectedCount === 0) {
            $('#confirmMultiPublishBtn').prop('disabled', true).addClass('opacity-50 cursor-not-allowed');
        } else {
            $('#confirmMultiPublishBtn').prop('disabled', false).removeClass('opacity-50 cursor-not-allowed');
        }
    } else {
        if (selectedCount > 0) {
            actionsDiv.removeClass('hidden');
            $('#confirmMultiPublishBtn').text(`发布到已选公众号(${selectedCount})`);
        } else {
            actionsDiv.addClass('hidden');
        }
    }
}

// 取消所有选择
function cancelMultiSelection() {
    $('.wechat-account-card .multi-select-checkbox.selected').each(function () {
        $(this).removeClass('selected bg-green-500 border-green-500');
        $(this).empty();
        $(this).closest('.wechat-account-card').removeClass('border-green-500 shadow-green-200');
    });
    // 清空选中列表
    selectedAccounts = [];
    updateMultiSelectActions();
}

// 确认批量发布到多个公众号 - 优化批量文档提示
function confirmMultiPublish() {
    // 直接使用全局选中列表
    if (selectedAccounts.length === 0) {
        alert('请先选择要发布的公众号');
        return;
    }

    const documentId = sessionStorage.getItem('currentDocumentId');
    const documentTitle = sessionStorage.getItem('currentDocumentTitle');

    // 检查是否为批量发布
    if (documentId === 'batch') {
        // 批量发布多个文档到多个公众号
        const batchDocuments = JSON.parse(sessionStorage.getItem('batchDocuments') || '[]');
        if (batchDocuments.length === 0) {
            alert('没有选中的文档，请重新选择');
            return;
        }

        // 优化提示信息，显示更详细的统计
        if (confirm(`确定要将 ${batchDocuments.length} 个文档批量创建草稿到 ${selectedAccounts.length} 个公众号吗？\n\n总计将创建 ${batchDocuments.length * selectedAccounts.length} 个草稿`)) {
            hideWechatAuthModal();
            publishToMultipleAccounts(selectedAccounts, true);
        }
    } else {
        // 发布单个文档到多个公众号
        if (confirm(`确定要将文档：${documentTitle} 创建草稿到 ${selectedAccounts.length} 个公众号吗？`)) {
            hideWechatAuthModal();
            publishToMultipleAccounts(selectedAccounts, false);
        }
    }
}

// 发布到多个公众号
function publishToMultipleAccounts(accounts, isBatchDocuments) {
    const documentId = sessionStorage.getItem('currentDocumentId');
    const documentTitle = sessionStorage.getItem('currentDocumentTitle');
    const totalAccounts = accounts.length;

    if (totalAccounts === 0) {
        alert('请选择要发布的公众号');
        return;
    }

    // 优化加载提示
    const batchDocuments = isBatchDocuments ? JSON.parse(sessionStorage.getItem('batchDocuments') || '[]') : [];
    const totalTasks = isBatchDocuments ? batchDocuments.length * totalAccounts : totalAccounts;
    showLoadingOverlay(`正在发布（共 ${totalTasks} 个任务）...`);

    // 准备请求数据
    const requestData = {
        accountIds: accounts.map(acc => acc.id)
    };

    if (isBatchDocuments) {
        // 批量文档模式
        requestData.documents = batchDocuments;
        if (requestData.documents.length === 0) {
            hideLoadingOverlay();
            alert('没有选中的文档');
            return;
        }
    } else {
        // 单个文档模式
        requestData.documentId = documentId;
        if (!requestData.documentId) {
            hideLoadingOverlay();
            alert('文档ID无效');
            return;
        }
    }

    // 发送请求到新的多公众号发布接口
    const url = isBatchDocuments ? '/api/documents/batch-publish-to-multiple-wechat' : '/api/documents/publish-to-multiple-wechat';

    console.log('发送多公众号发布请求:', {
        url: url,
        accounts: accounts,
        requestData: requestData
    });

    $.ajax({
        url: url,
        type: 'POST',
        data: JSON.stringify(requestData),
        contentType: 'application/json',
        success: function (response) {
            hideLoadingOverlay();
            if (response.code === 0) {
                // 构建队列消息
                let message = isBatchDocuments ?
                    `已成功加入到队列，任务ID: ${response.taskId}\n\n批量文档已提交到队列处理` :
                    `已成功加入到队列，任务ID: ${response.taskId}\n\n文档：${documentTitle} 已提交到队列处理`;

                alert(message);
                
                // 清空批量文档数据
                if (isBatchDocuments) {
                    sessionStorage.removeItem('batchDocuments');
                }

                // 为了实现队列完成的通知，我们需要定期轮询任务状态
                // 这里我们假设需要一个检查任务状态的函数，将在后续实现
                console.log('任务已提交到队列，任务ID:', response.taskId);
                console.log('提示：需要实现任务状态轮询来通知用户任务完成');
                
                // 临时模拟：几秒后显示任务完成提示
                setTimeout(function() {
                    let completeMessage = isBatchDocuments ?
                        `批量文档发布任务已完成！` :
                        `文档：${documentTitle} 已成功发布！`;
                    alert(completeMessage);
                    
                    // 刷新文档列表
                    if (typeof loadDocuments === 'function') {
                        loadDocuments();
                    }
                }, 10000); // 10秒后模拟完成
                
                // 清空选中列表
                selectedAccounts = [];
            } else {
                alert(`多公众号发布失败：${response.message || '未知错误'}`);
            }
        },
        error: function (xhr, status, error) {
            hideLoadingOverlay();
            console.error('多公众号发布请求失败:', error);
            alert(`多公众号发布请求失败：${error || '网络错误'}`);
        }
    });
}

// 发布到选择的公众号 - 批量模式下禁用单选发布
function publishToSelectedAccount(accountId, accountName) {
    const documentId = sessionStorage.getItem('currentDocumentId');
    const documentTitle = sessionStorage.getItem('currentDocumentTitle');

    // 检查是否为批量发布 - 批量模式下不允许单选发布，强制使用多选
    if (documentId === 'batch') {
        alert('批量文档模式请使用多选功能，选择多个公众号后点击"发布到已选公众号"');
        $(`.wechat-account-card[data-account-id="${accountId}"]`).removeClass('processing');
        return;
    }

    // 检查documentId是否有效
    if (!documentId || documentId === 'undefined' || documentId === '') {
        alert('无法发布文档到公众号：缺少文档ID，请刷新页面后重试');
        hideWechatAuthModal();
        return;
    }

    if (confirm(`确定要将文档：${documentTitle} 创建草稿到公众号：${accountName} 吗？`)) {
        hideWechatAuthModal();
        showLoadingOverlay('正在创建草稿到公众号...');

        console.log('发送发布请求:', {
            url: `/api/documents/${documentId}/publish-to-wechat`,
            accountId: accountId,
            requestData: { officialAccountId: accountId }
        });

        $.ajax({
            url: `/api/documents/${documentId}/publish-to-wechat`,
            type: 'POST',
            data: JSON.stringify({ officialAccountId: accountId }),
            contentType: 'application/json',
            success: function (response) {
                hideLoadingOverlay();
                if (response.code === 0) {
                    // 草稿创建成功
                    let message = `文档：${documentTitle} 已成功创建草稿到公众号：${accountName}`;
                    if (response.mediaId) {
                        message += `\n\n草稿ID: ${response.mediaId}`;
                    }
                    message += '\n\n您可以在微信公众号后台查看并发布此草稿。';
                    alert(message);
                } else {
                    // 失败
                    alert(`草稿创建失败：${response.message || '未知错误'}`);
                }
            },
            error: function (xhr, status, error) {
                hideLoadingOverlay();
                console.error('发布到公众号失败:', error);
                alert(`发布到公众号失败：${error || '网络错误'}`);
            }
        });
    } else {
        // 取消确认时移除processing状态
        $(`.wechat-account-card[data-account-id="${accountId}"]`).removeClass('processing');
    }
}

// 处理批量发布 - 兼容旧逻辑，实际已被多公众号批量发布替代
function handleBatchPublish(accountId, accountName) {
    const batchDocuments = JSON.parse(sessionStorage.getItem('batchDocuments') || '[]');

    if (batchDocuments.length === 0) {
        alert('没有选中的文档，请重新选择');
        hideWechatAuthModal();
        return;
    }

    // 提示用户使用多选功能
    if (confirm(`您正在使用旧版批量发布功能（单个公众号）。\n\n若需发布到多个公众号，请取消后使用多选功能。\n\n确定要将 ${batchDocuments.length} 个文档批量创建草稿到公众号：${accountName} 吗？`)) {
        hideWechatAuthModal();
        showLoadingOverlay(`正在批量创建 ${batchDocuments.length} 个草稿到公众号...`);

        console.log('发送批量发布请求:', {
            url: '/api/documents/batch-publish-to-wechat',
            accountId: accountId,
            documents: batchDocuments
        });

        $.ajax({
            url: '/api/documents/batch-publish-to-wechat',
            type: 'POST',
            data: JSON.stringify({
                officialAccountId: accountId,
                documents: batchDocuments
            }),
            contentType: 'application/json',
            success: function (response) {
                hideLoadingOverlay();
                if (response.code === 0) {
                    const successCount = response.successCount || 0;
                    const failCount = response.failCount || 0;
                    let message = `批量发布完成！\n\n成功：${successCount} 个\n失败：${failCount} 个`;

                    if (response.details && response.details.length > 0) {
                        message += '\n\n详细信息：';
                        response.details.forEach(detail => {
                            message += `\n${detail.title}: ${detail.success ? '成功' : '失败'}`;
                            if (!detail.success && detail.error) {
                                message += ` (${detail.error})`;
                            }
                        });
                    }

                    message += '\n\n您可以在微信公众号后台查看并发布这些草稿。';
                    alert(message);

                    // 清空批量文档数据
                    sessionStorage.removeItem('batchDocuments');

                    // 刷新文档列表
                    if (typeof loadDocuments === 'function') {
                        loadDocuments();
                    }
                } else {
                    alert(`批量发布失败：${response.message || '未知错误'}`);
                }
            },
            error: function (xhr, status, error) {
                hideLoadingOverlay();
                console.error('批量发布到公众号失败:', error);
                alert(`批量发布到公众号失败：${error || '网络错误'}`);
            }
        });
    }
}

// 根据公众号类型获取文本
function getAccountTypeText(type) {
    switch (type) {
        case 1:
            return '订阅号';
        case 2:
            return '服务号';
        default:
            return '未知类型';
    }
}

// 根据授权状态获取文本
function getAuthStatusText(status) {
    // 现在status可能是文本值，直接返回
    if (typeof status === 'string') {
        return status;
    }
    // 保持对数字状态的兼容
    switch (status) {
        case 1:
            return '正常授权';
        case 2:
            return '已过期';
        case 3:
            return '已取消';
        default:
            return '未知状态';
    }
}

// 根据授权状态获取样式类
function getAuthStatusClass(status) {
    // 处理文本类型的status
    if (typeof status === 'string') {
        if (status.includes('已授权') || status.includes('正常')) {
            return 'bg-green-500';
        } else if (status.includes('过期')) {
            return 'bg-yellow-500';
        } else if (status.includes('取消')) {
            return 'bg-red-500';
        } else {
            return 'bg-gray-500';
        }
    }
    // 保持对数字状态的兼容
    switch (status) {
        case 1:
            return 'bg-green-500';
        case 2:
            return 'bg-yellow-500';
        case 3:
            return 'bg-red-500';
        default:
            return 'bg-gray-500';
    }
}

// 显示手动添加公众号弹窗
function showAuthQRCodeModal() {
    if ($('#authQRCodeModal').length === 0) {
        const manualAuthModalHtml = `
            <div id="authQRCodeModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
                <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden transform transition-all scale-95 hover:scale-100 duration-200">
                    <div class="p-6">
                        <div class="flex justify-between items-center mb-4">
                            <h2 class="text-xl font-bold text-gray-800">添加公众号</h2>
                            <button id="closeQRCodeModalBtn" class="text-gray-400 hover:text-gray-600 transition">
                                <i class="fa fa-times text-xl"></i>
                            </button>
                        </div>
                        <div class="space-y-4">
                            <div>
                                <label class="block text-gray-700 text-sm font-medium mb-1" for="accountName">
                                    公众号名称
                                </label>
                                <input id="accountName" type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入公众号名称">
                            </div>
                            <div>
                                <label class="block text-gray-700 text-sm font-medium mb-1" for="appId">
                                    AppID
                                </label>
                                <input id="appId" type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入公众号AppID">
                            </div>
                            <div>
                                <label class="block text-gray-700 text-sm font-medium mb-1" for="appSecret">
                                    AppSecret
                                </label>
                                <input id="appSecret" type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入公众号AppSecret">
                            </div>
                            <div class="pt-2">
                                <button id="submitManualAuthBtn" class="w-full bg-green-500 hover:bg-green-600 text-white font-medium py-2 px-4 rounded-lg transition duration-300 ease-in-out flex items-center justify-center">
                                    <i class="fa fa-save mr-2"></i>
                                    保存公众号信息
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        $('body').append(manualAuthModalHtml);
        $('#closeQRCodeModalBtn').on('click', hideAuthQRCodeModal);
        $('#submitManualAuthBtn').on('click', submitManualAuth);
    }
    $('#authQRCodeModal').removeClass('hidden');
}

// 隐藏授权弹窗
function hideAuthQRCodeModal() {
    $('#authQRCodeModal').addClass('hidden');
}

// 提交手动添加的公众号信息
function submitManualAuth() {
    const accountName = $('#accountName').val().trim();
    const appId = $('#appId').val().trim();
    const appSecret = $('#appSecret').val().trim();

    // 简单的表单验证
    if (!accountName) {
        alert('请输入公众号名称');
        return;
    }
    if (!appId) {
        alert('请输入公众号AppID');
        return;
    }
    if (!appSecret) {
        alert('请输入公众号AppSecret');
        return;
    }

    showLoadingOverlay('正在保存公众号信息...');

    // 调用后端API保存公众号信息
    $.ajax({
        url: '/api/documents/wechat/add-manual-account',
        type: 'POST',
        data: JSON.stringify({
            accountName: accountName,
            appId: appId,
            appSecret: appSecret
        }),
        contentType: 'application/json',
        success: function (response) {
            hideLoadingOverlay();
            if (response.code === 0) {
                hideAuthQRCodeModal();
                // 清空表单
                $('#accountName').val('');
                $('#appId').val('');
                $('#appSecret').val('');
                alert('公众号添加成功！');
                loadWechatAccounts();
            } else {
                alert('添加失败：' + (response.message || '未知错误'));
            }
        },
        error: function (xhr, status, error) {
            hideLoadingOverlay();
            console.error('保存公众号信息失败:', error);
            alert(`保存公众号信息失败：${error || '网络错误'}`);
        }
    });
}

// 显示加载遮罩
function showLoadingOverlay(message) {
    if ($('#loadingOverlay').length === 0) {
        const loadingHtml = `
            <div id="loadingOverlay" class="fixed inset-0 bg-black bg-opacity-40 flex items-center justify-center z-50 hidden">
                <div class="bg-white p-8 rounded-2xl shadow-lg flex flex-col items-center space-y-4">
                    <div class="fa fa-spinner fa-spin text-4xl text-blue-500"></div>
                    <p id="loadingMessage" class="text-gray-700 font-medium">${message || '处理中...'}</p>
                </div>
            </div>
        `;
        $('body').append(loadingHtml);
    } else {
        $('#loadingMessage').text(message || '处理中...');
    }
    $('#loadingOverlay').removeClass('hidden');
}

// 隐藏加载遮罩
function hideLoadingOverlay() {
    $('#loadingOverlay').addClass('hidden');
}

// 发布文档到公众号
function publishToWechat(accountId, accountName) {
    // 这个函数是publishToSelectedAccount的重复定义，直接调用它确保代码统一
    publishToSelectedAccount(accountId, accountName);
}